<template>
  <div>
    <public-modal
      width="600px"
      :footer="false"
      :title="title"
      :publicVisible="publicVisible"
      @handleOk="handleOk"
      @cancel="publicVisible = false"
    >
      <div slot="content" class="content">
        <a-tree
          checkable
          :tree-data="treeData"
          :expandedKeys="expandedKeys"
          :checkedKeys="checkedKeys"
          :selectedKeys="selectedKeys"
          :replace-fields="replaceFields"
          @check="onCheck"
          @expand="onExpand"
        >
        </a-tree>
      </div>
    </public-modal>
  </div>
</template>

<script>
import publicModal from '@/components/publicModal'
export default {
  name: 'regionalTreeModal',
  components: { publicModal },
  data() {
    return {
      title: '管辖区域',
      publicVisible: false,
      expandedKeys: [],
      selectedKeys: [],
      checkedKeys: [],
      treeData: [],
      replaceFields: {
        key: 'id',
        title: 'xcName',
        children: 'communityList',
      },
    }
  },
  mounted() {},
  methods: {
    show(record, idset) {
      this.treeData = record
      this.checkedKeys = idset
      this.expandedKeys = idset
      this.publicVisible = true
    },

    handleOk() {
      const b = this.checkedKeys
        .map((item) => {
          const node = this.getNodeById(this.treeData, item)
          if (node.isSon) {
            return { sqjwhFDzbm: node.id, sqjwhFSqjcwhmc: node.xcName }
          }
        })
        .filter((item) => item !== undefined)

      const c = b
        .map((item) => {
          return item.sqjwhFSqjcwhmc
        })
        .join(',')

      this.$emit('update', b, c)
      this.publicVisible = false
    },

    getNodeById(data, id) {
      for (const item of data) {
        if (item.id === id) return item
        if (item.communityList) {
          const res = this.getNodeById(item.communityList, id)
          if (res) return res
        }
      }
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
    },

    onCheck(checkedKeys, info) {
      this.checkedKeys = checkedKeys
    },
  },
}
</script>

<style scoped lang="less">
.content {
  height: auto;
}
</style>
